﻿/*
=======================================================
    MHCheck【检测报告】
=======================================================
*/

using Microsoft.AspNetCore.Mvc;

namespace Services
{
    public interface IMHCheckLogic : ILogic<MHCheckModel, MHCheckFilterModel>
    {
        Task<long?> GetLastCheckTime(int deviceId);
    }

    public class MHCheckLogic : BaseLogic<MHCheckModel, MHCheckFilterModel, MHCheck, IMHCheckRepository, IMHCheckMapping, IMHCheckService>, IMHCheckLogic
    {
        #region Ioc
        IMagnetHeadRepository _MagnetHeadRepository;
        IMagnetHeadMapping _MagnetHeadMapping;
        public MHCheckLogic(ICurrentUser currentUser, IMHCheckRepository repository, IMHCheckMapping mapping, IMHCheckService service,
            IMagnetHeadRepository magnetHeadRepository,
            IMagnetHeadMapping magnetHeadeMapping)
            : base(currentUser, repository, mapping, service)
        {
            _MagnetHeadRepository = magnetHeadRepository;
            _MagnetHeadMapping = magnetHeadeMapping;
        }
        #endregion

        public async Task<long?> GetLastCheckTime(int deviceId)
        {
            return await _repository.GetLastCheckTime(deviceId);
        }
        public override PageModel<MHCheckModel> GetPage(MHCheckFilterModel filterModel, int pageIndex = 1, int pageSize = 20, string orderBy = null)
        {
            var (items, totalCount) = _repository.GetPage(_mapping.FilterModel2Where(filterModel), pageIndex, pageSize, orderBy);

            var ItemsTemp = _mapping.Entity2Model(items);

            var mhIds = ItemsTemp.Select(x => x.MHID).Distinct().ToList();
            var where = Expressionable.Create<MagnetHead>().And(x => mhIds.Contains(x.MHID));
            var magnetHeads = _MagnetHeadMapping.Entity2Model(_MagnetHeadRepository.GetSearch(where))
                .ToDictionary(x => x.MHID, x => x.DeviceID);

            foreach (var item in ItemsTemp)
            {
                if (magnetHeads.TryGetValue(item.MHID, out var deviceId))
                {
                    item.DeviceID = deviceId;
                }
            }

            return new PageModel<MHCheckModel>
            {
                Items = ItemsTemp,
                TotalCount = totalCount
            };
        }
    }
}